package com.apes.framework.plugin.filereader.xml;

import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.filereader.FileReader;
import com.apes.framework.plugin.log.timer.Timer;
import com.apes.framework.util.ClassPathScanUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.util.concurrent.Executors;

/**
 * 功能：Esb文件解析器
 *
 * @author xul
 * @create 2017-12-05 14:05
 */
@Component
@Slf4j
public class XmlFileReader extends FileReader {
    private final String[] packages = {"com.apes"};
    private static final String suffix = ".xml";
    private SAXReader reader = new SAXReader();

    @Override
    public String getSuffix() {
        return suffix;
    }

    @Override
    public String[] getPackages() {
        return this.packages;
    }

    @Timer("Xml解析")
    public void init() {
        try {
            read();
            String configFilePath = String.format("%s/form", ClassPathScanUtil.getConfigFilePath()); /** 读取外部配置文件 **/
            if (configFilePath != null) {
                refreshFile(configFilePath);
                /** 实时监听config/form目录下文件的变化 **/
                Executors.newCachedThreadPool().execute(new ResourceListener(configFilePath) {
                    @Override
                    void execute(WatchKey watchKey, WatchEvent event) {
                        //System.out.println(event.context().toString() + " => " + event.kind());
                        refreshFile(watchKey.watchable().toString());
                    }
                });
            }
        } catch (Exception ex) {
            logger.error(ex);
        }
    }

    /**
     * 功能：xml文件解析
     */
    public void parse(InputStream is, String fileAbsolutePath) throws Exception {
        if (is == null) return;
        try {
            Document document = reader.read(is);
            SpringManager.getBean(ApesXmlParser.class).parse(document);
        } catch (Exception e){
            //logger.error(e);
        }
    }

}
